package com.aiyige.page.revisionnotification;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.request.AgreementRequest;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.ToastX;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.RevisionNotificationPage)
public class RevisionNotificationPage extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.revision_notification_page);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
    }

    @OnClick({R.id.foregroundIv, R.id.confirmBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.foregroundIv:
                ARouter.getInstance()
                        .build(ARouterConfig.WebViewPage)
                        .withString("url", BuildConfig.userAgreementsUrl)
                        .withBoolean("noTitleBar", false)
                        .withBoolean("disableNav", false)
                        .navigation(this);
                break;
            case R.id.confirmBtn:
                new ConfirmTask(this).execute();
                break;
        }
    }


    public class ConfirmTask extends SafeAsyncTask<Object, Object, Object> {

        public ConfirmTask(Activity activity) {
            super(activity, true, "");
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                finish();
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().userAgreements(AgreementRequest.newBuilder()
                        .type(AgreementRequest.TYPE_USER_SERVICE)
                        .build()).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }

        }
    }
}
